<?php
class DevDefAction extends ZMAction {
    /**
    * 获取设备定义列表
    * 
    */
    public function index(){
        $start = $_REQUEST['start'];
        $limit = $_REQUEST["limit"];
        $sort = $_REQUEST['sort'];
        $dir = $_REQUEST['dir'];
        $cid = $_REQUEST['cid'];
        if(!is_numeric($start)){
            $start = 0;
        }
        if(!is_numeric($limit)){
            $limit = 20;
        }
        $Model = M('DevDef');
        $ModelCatalgItems = M('CatalogItems');
        if($cid == -1){
            $subSql = $ModelCatalgItems->field('ddid')->select(false);
            $where['_string'] = "ddid not in $subSql";
        }else{
            $subSql = $ModelCatalgItems->field('ddid')->where("cid=$cid")->select(false);
            $where['_string'] = "ddid in $subSql";
        }
        $count = $Model->where($where)->count();
        $result = $Model->where($where)->limit("$start,$limit")->select();
        $this->ajaxRetArray($result,$count);
    }
    
    /**
    * 获取设备属性列表
    * 
    * @param mixed $devid
    */
    protected function getDefAttr($ddid){
        $Model = M('DevAttrDef');
        $actDev = A('Dev');
        $ModelDev = M('DevDef');
        $ModelEnum = M('ValTypeComboEnum');
        $where['ddid'] = $ddid;
        $result = $Model->where($where)->select();
        foreach($result as &$row){
            $resAttr = $this->getValue($row['vtid'],$row['defval']);
            if($resAttr){
                $row['editor'] = $resAttr['editor'];
                $row['defval'] = $resAttr['value'];    
                if($resAttr['editor'] == 'devfield'){ //递归的
                    //获取设备名称作为值
                    $resDev = $ModelDev->where("ddid=".$row['defval'])->find();
                    if($resDev){
                        $row['valdesc'] = $resDev['ddname'];
                    }
                    
                    $childrens = $actDev->getDevAttr($row['devid']);
                    if($childrens){
                        $row['children'] = $childrens;
                        $row['expanded'] = true;
                    }else{
                        $row['leaf'] = true;
                    }
                }else if($row['editor'] == 'combo'){
                    if(!empty($row['defval'])){
                        $map['vtid'] = $row['vtid'];
                        $map['id'] = $row['defval'];
                        $res = $ModelEnum->where($map)->find();
                        if($res){
                            $row['valdesc'] = $res['val'];
                        }
                    }
                    $row['leaf'] = true;
                }else{
                    $row['valdesc'] = $resAttr['value'];
                    $row['leaf'] = true;
                }                
            }
            $row['iconCls'] = 'mattr';
        }
        return $result;
    }
    
    /**
    * 获取设备属性列表
    * 
    */
    public function getAttr(){
        $ddid = $_REQUEST['ddid'];
        echo json_encode($this->getDefAttr($ddid));
    }
    
    protected function setDevAttrVisible($devid,$attrid,$isvisible){
        $model = M('DevAttr');
        $data['isvisible'] = $isvisible;
        $model->where("devid=$devid and attrid=$attrid")->save($data);
    }
    
    protected function setDevAttrByArray($devid,$attrs){
        if($devid !== false){
            foreach($attrs as $row){
                if($row['data']['editor']=='devfield'){
                    $childDevId = $this->getDevAttrVal($devid,$row['data']['attrid']);
                    $this->setDevAttrByArray($childDevId['value'],$row['children']);
                    $this->setDevAttrVisible($devid,$row['data']['attrid'],(empty($row['data']['isvisible'])?0:1));   
                }else{
                    $this->setDevAttrValue($devid,$row['data']['attrid'],$row['data']['defval'],(empty($row['data']['isvisible'])?0:1));
                }
            }
        }
    }
    
    /**
    * 设置属性缺省值
    * 
    * @param mixed $attrid
    * @param mixed $value
    */
    protected function setAttrDef($attrid,$value){
        
    }
    
    public function save(){
        $model = M('DevDef');
        $modelTypeDef = M('ValTypeDef');
        $ddid = $_REQUEST['ddid'];
        
        $data = $model->create();
        
//        $model->startTrans();
        if(empty($ddid)){
            $ddid = $model->add($data);
            if($ddid===false){
                $this->error('保存错误!');
                return;
            }
        }else{
            $model->save($data);
        }
        
        $strAttrs = str_replace("\\\"","\"",$_REQUEST['attrs']);
        $strAttrs = str_replace("\\\\","\\",$strAttrs);
        $attrs = json_decode($strAttrs,true);
        
        $actDev = A('Dev');
        $modelAttr = M('DevAttrDef');
        $attrids = array();
        foreach($attrs as $row){
            $val = false;
            if($row['data']['editor']=='devfield'){
                $val = $actDev->createDev(0,$row['data']['defval'],$row['data']['attrname'],1);
                if($val!==false){
                    $this->setDevAttrByArray($val,$row['children']);   
                }
            }
            if(empty($row['data']['attrid'])){
                unset($data);
                $data['ddid'] = $ddid;
                $data['attrname'] = $row['data']['attrname'];
                $data['vtid'] = $row['data']['vtid'];
                $data['memo'] = $row['data']['memo'];
                $data['isvisible'] = empty($row['data']['isvisible'])?0:1;
                $valid = $this->addValue($row['data']['vtid'],$row['data']['defval']);
                if($valid!==false){
                    $data['defval'] = $valid;
                }
                if($val!==false) $data['devid'] = $val;
                $attrid = $modelAttr->add($data);
                $attrids[] = $attrid;                    
            }else{
                $attrid = $row['data']['attrid'];
                $resAttr = $modelAttr->where("attrid=$attrid")->find();
                if($resAttr){
                    $this->delValue($resAttr['vtid'],$resAttr['defval'],$resAttr['devid']);
                }
                unset($data);
                $data['ddid'] = $ddid;
                $data['attrname'] = $row['data']['attrname'];
                $data['vtid'] = $row['data']['vtid'];
                $data['memo'] = $row['data']['memo'];
                $data['isvisible'] = empty($row['data']['isvisible'])?0:1;
                $valid = $this->addValue($row['data']['vtid'],$row['data']['defval']);
                if($valid!==false){
                    $data['defval'] = $valid;
                }
                if($val!==false) $data['devid'] = $val;
                $modelAttr->where("attrid=$attrid")->save($data);
                $attrids[] = $attrid;                    
            }
        }
        //要删除没有的属性
        $map['ddid'] = $ddid;
        $map['attrid'] = array('not in',$attrids);
        $resOldAttr = $modelAttr->where($map)->select();
        foreach($resOldAttr as $row){
            $this->delValue($row['vtid'],$row['defval'],$row['devid']); //同时要删除值
        }
        $modelAttr->where($map)->delete();
        
        $cid = $_REQUEST['cid'];
        if($cid != -1){
            $ModelCatalogItems = M('CatalogItems');
            unset($data);
            $data['cid'] = $cid;
            $data['ddid'] = $ddid;
            $ModelCatalogItems->add($data);
        }
        
        $this->success('ok');

//        $modelAttr = M('DevAttrDef');
//        $attrids = array();
//        foreach($attrs as $row){
//            if(empty($row['attrid'])){
//                $resType = $modelTypeDef->where('vtid='.$row['vtid'])->find();
//                if($resType){
//                    $modelVal = M($resType['ValTable']);
//                    unset($m);
//                    $m['val'] = $row['defval'];
//                    $valid = $modelVal->add($m);                 

//                    unset($data);
//                    $data['ddid'] = $ddid;
//                    $data['attrname'] = $row['attrname'];
//                    $data['vtid'] = $row['vtid'];
//                    if($valid!==false){
//                        $data['defval'] = $valid;
//                    }
//                    $attrid = $modelAttr->add($data);
//                    $attrids[] = $attrid;
//                } 
//            }else{
//                $attrid = $row['attrid'];
//                $resAttr = $modelAttr->where("attrid=$attrid")->find();
//                if($resAttr){
//                    $valid = false;
//                    if($row['vtid'] != $resAttr['vtid']){ //如果类型变过了的话,需要先删除，再添加
//                        $resType = $modelTypeDef->where('vtid='.$resAttr['vtid'])->find();
//                        if($resType){
//                            $modelVal = M($resType['ValTable']);
//                            $modelVal->where('id='.$row['defval'])->delete();
//                        }
//                        $resType = $modelTypeDef->where('vtid='.$row['vtid'])->find();
//                        if($resType){
//                            $modelVal = M($resType['ValTable']);
//                            unset($m);
//                            $m['val'] = $row['defval'];
//                            $valid = $modelVal->add($m);
//                        }
//                    }else{ //如果类型相同的话，仅更新
//                        $resType = $modelTypeDef->where('vtid='.$row['vtid'])->find();
//                        if($resType){
//                            $modelVal = M($resType['ValTable']);
//                            if(is_numeric($resAttr['defval'])){
//                                $resVal = $modelVal->where('id='.$resAttr['defval'])->find();
//                                if($resVal){
//                                    unset($m);
//                                    $m['id'] = $resVal['id'];
//                                    $m['val'] = $row['defval'];
//                                    $modelVal->save($m);
//                                    $valid = $resVal['id'];
//                                }else{
//                                    unset($m);
//                                    $m['val'] = $row['defval'];
//                                    $valid = $modelVal->add($m);                                   
//                                }
//                            }else{
//                                unset($m);
//                                $m['val'] = $row['defval'];
//                                $valid = $modelVal->add($m);
//                            }
//                        } 
//                    }
//                    
//                    unset($data);
//                    $data['ddid'] = $ddid;
//                    $data['attrname'] = $row['attrname'];
//                    $data['vtid'] = $row['vtid'];
//                    if($valid!==false){
//                        $data['defval'] = $valid;
//                    }
//                    $modelAttr->where("attrid=$attrid")->save($data);
//                }
//                $attrids[] = $attrid;
//            }
//        }
        //要删除没有的属性
//        $map['ddid'] = $ddid;
//        $map['attrid'] = array('not in',$attrids);
//        $resOldAttr = $modelAttr->where($map)->select();
//        foreach($resOldAttr as $row){
//            $vtid = $row['vtid'];
//            if(is_numeric($row['defval'])){
//                $resType = $modelTypeDef->where('vtid='.$row['vtid'])->find();
//                if($resType){
//                    $modelVal = M($resType['ValTable']);
//                    $modelVal->where('id='.$row['defval'])->delete();
//                }   
//            }
//        }
//        $modelAttr->where($map)->delete();
//        
//        $this->success('ok');
    }
    
    public function delDevDef($ddid){
        if($ddid==C('XYZ')) return;
        if($ddid==C('PORTINFO')) return;
        
        $modelDevDef = M('DevDef');
        $modelAttr = M('DevAttrDef');
        $map['ddid'] = $ddid;
        $resAttr = $modelAttr->where($map)->select();
        foreach($resAttr as $row){
            $this->delValue($row['vtid'],$row['defval'],$row['devid']); //同时要删除值
        }
        $modelAttr->where($map)->delete();
        $modelDevDef->where($map)->delete();
        
        //删除分类里面的信息
        $Model = M('CatalogItems');
        $Model->where("ddid=$ddid")->delete();
    }
    
    public function del(){
        $ids = $_REQUEST['ids'];
        $idArr = explode(',',$ids);
        foreach($idArr as $ddid){
            $this->delDevDef($ddid);
        }
        $this->success('删除成功！');
    }
    
    public function getEnum(){
        $Model = M('DevDef');
        $result = $Model->field(array('ddid'=>'id','ddname'=>'text'))->select();        
        $this->ajaxRetArray($result);
    }
    
    public function catalog(){
        $parentid = $_REQUEST['node'];
        $result = $this->getCatalog($parentid,false,true);
        echo(json_encode($result));  
    }
    
    protected function getCatalog($parentid,$bRecursion=false,$bShowNoGroup=false){
        $Model = M('Catalog');
        $map['parentid'] = $parentid;
        $result = $Model->where($map)->select();
        if($result){
            foreach($result as &$item){
                $item['id'] = $item['cid'];
                $item['text'] = $item['catname'];
                $item['cls'] = 'group';
                $childNodes = $Model->where("parentid='". $item['cid']."'")->count();
                if(empty($childNodes)){
                    //$item['leaf'] = true;
                }else{
                    if($bRecursion){
                        $item['children'] = $this->getCatalog($item['cid'],true);
                        $item['expanded'] = true;
                    }else{
                        $item['expanded'] = false;
                    }
                }
            }
        }else{
            $result = array();
        }     
        if($bShowNoGroup && ($parentid==0)){
            $nogroup = array(
                'id' => -1,
                'text' => '未分组模型',
                'cls' => 'group',
                'leaf' => true,
                'cid'=> -1,
                'catname' => '未分组模型',
                'parentid' => 0,
                'memo' => '',
            );
            array_push($result,$nogroup);
        }
        return $result;
    }
    
    public function catalogall(){
        $result = $this->getCatalog($_REQUEST['node'],true);
        echo(json_encode($result));  
    }
    
    public function saveCat(){
        $cid = $_REQUEST['cid'];
        $parentid = $_REQUEST['parentid'];
        
        $Model = M('Catalog');
        $data = $Model->create();
        if(empty($cid)){
            $cid = $Model->add($data);
            $data['add'] = true;
        }else{
            $Model->save($data);
            $data['add'] = false;
        }
        $data['cid'] = $cid;
        $data['id'] = $cid;
        $data['text'] = $data['catname'];
        $this->ajaxReturn($data,'ok',true);
    }
    
    protected function doDelCat($cid){
        $modelCat = M('Catalog');
        $modelItems = M('CatalogItems');
        $res = $modelCat->where("parentid=$cid")->select();
        foreach($res as $row){
            $this->doDelCat($row['cid']); //递归删除下属分类
        }
        $modelCat->where("cid=$cid")->delete();
        $modelItems->where("cid=$cid")->delete();
    }
    
    public function delCat(){
        $cid = $_REQUEST['cid'];
        $this->doDelCat($cid);
        $data['cid'] = $cid;
        $this->ajaxReturn($data,'ok',true);
    }
    
    public function dropCat(){
        $Model = M('CatalogItems');
        $cid = $_REQUEST['cid'];
        $ids = $_REQUEST['ids'];
        $add = $_REQUEST['add'];
        $sid = $_REQUEST['sid'];
        
        $idsArr = explode(',',$ids);
        foreach($idsArr as $id){
            unset($data);
            $data['cid'] = $cid;
            $data['ddid'] = $id;
            $Model->add($data);
            
            if($add==0){
                unset($where);
                $where['cid'] = $sid;
                $where['ddid'] = $id;
                $Model->where($where)->delete();
            }
        }
        $this->success('ok');
    }
}